package com.example.shoppingmallclient;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@SuppressWarnings("all")
public class Login extends AppCompatActivity {

    private Button btnLogin;
    private EditText evUserNumber;
    private EditText evPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        findViews();
        setListeners();
    }

    private void findViews(){
        btnLogin = findViewById(R.id.btn_login);
        evUserNumber = findViewById(R.id.usernumber);
        evPassword = findViewById(R.id.password);
    }

    private void setListeners(){
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login(){
        new Thread(){
            @Override
            public void run() {
                //使用网络访问服务器端
                try {
                    URL url = new URL("http://10.7.88.84:8080/LoginServlet");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");


                    //获取用户名和密码的字符串
                    String userNumber = evUserNumber.getText().toString();
                    String password = evPassword.getText().toString();
                    System.out.println(userNumber);
                    String msg = userNumber + "," + password;
                    System.out.println(msg);
                    OutputStream os = connection.getOutputStream();
                    os.write(msg.getBytes());
                    os.flush(); //刷新缓存

                    //接收服务器发来的消息
                    InputStream is = connection.getInputStream();
                    StringBuffer stringBuffer = new StringBuffer();
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = is.read(bytes)) != -1){
                        stringBuffer.append(new String(bytes, 0, len));
                    }
                    Log.e("服务端响应的数据", stringBuffer.toString());

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}